/**
 * @param apiUrl api基地址
 * @param itemPageScrollTopArr 存储每个主题页的offetTop
 * @param clientHeight 屏幕高度
 */
let apiUrl = 'http://192.168.9.221:8082/canyin';
let itemPageScrollTopArr = [];
let clientHeight = 0;

function getClientHeight() {
    clientHeight = document.documentElement.clientHeight || window.clientHeight || document.body.clientHeight;
}

/**
 * 解决事件监听兼容性问题
 * @param elm {Object} dom节点
 * @param type {String} 事件类型, 不带'on'
 * @param callback 事件操作程序
 */
function addEvent(elm, type, callback) {
    if (elm.addEventListener) {
        elm.addEventListener(type, callback);
    } else {
        elm.attachEvent('on' + type, callback);
    }
}

// 封装Ajax请求
let Ajax = {
    get: function (url, fn) {
        let xhr = null;
        if (window.XMLHttpRequest) {
            xhr = new XMLHttpRequest();
        } else {
            //为了兼容IE6
            xhr = new ActiveXObject('Microsoft.XMLHTTP');
        }
        xhr.open('GET', url, true);
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && (xhr.status === 200 || xhr.status === 304)) {
                fn.call(this, xhr.responseText);
            }
        };
        xhr.send();
    },
    post: function (url, data, fn) {
        let xhr = null;
        if (window.XMLHttpRequest) {
            xhr = new XMLHttpRequest();
        } else {
            //为了兼容IE6
            xhr = new ActiveXObject('Microsoft.XMLHTTP');
        }
        xhr.open('POST', url, true);
        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && (xhr.status === 200 || xhr.status === 304)) {
                fn.call(this, xhr.responseText);
            }
        };
        xhr.send(data);
    }
};

// 请求首页信息接口
function getResponse() {
    let logoImg = document.getElementById('logo');
    let wxCode = document.getElementsByClassName('wxCode');
    let wbCode = document.getElementsByClassName('wbCode');
    let wxUrl = document.getElementById('wxUrl');
    let wbUrl = document.getElementById('wbUrl');
    let wxUrl2 = document.getElementById('wxUrl2');
    let wbUrl2 = document.getElementById('wbUrl2');
    Ajax.get(apiUrl + '/api/configure/getConfigure', function (data) {
        let response = JSON.parse(data).data;
        logoImg.src = apiUrl + response['logoUrl'];
        wxUrl.href = response['wechatLink'];
        wbUrl.href = response['weiboLink'];
        wxUrl2.href = response['wechatLink'];
        wbUrl2.href = response['weiboLink'];
        for (let i = 0; i < wxCode.length; i++) {
            wxCode[i].src = apiUrl + response['wechatQrCodeUrl'];
        }
        for (let i = 0; i < wbCode.length; i++) {
            wbCode[i].src = apiUrl + response['weiboQrCodeUrl'];
        }
        renderSwiper(response['rotationChartList']);
        renderBrandStoryDocument(response['brandStoryDocument']);
        renderNavigationBar(response['daohanglanList']);
        checkItemPageNodeInfo();
    });
}

// 请求连锁加盟信息接口
function getLeague() {
    let hotLine = document.getElementById('hotLine');
    Ajax.get(apiUrl + '/api/league/getLeague', function (data) {
        let response = JSON.parse(data).data;
        hotLine.innerText = response.leagueHotline;
    });
}

// 请求官方信息接口
function getOfficialInfo() {
    let companyName = document.getElementById('company-name');
    let companyAddress = document.getElementById('company-address');
    let companyICP = document.getElementById('company-ICP');
    let companyMobile = document.getElementById('company-mobile');
    let companyContent = document.getElementById('company-content');
    Ajax.get(apiUrl + '/api/officialInfo/getOfficialInfo', function(data) {
        let response = JSON.parse(data).data;
        companyContent.innerHTML = response.content;
        companyName.innerText = response.name;
        companyAddress.innerText = response.address;
        companyICP.innerText = response.icp;
        companyMobile.innerText = response.mobile;
        checkItemPageNodeInfo();
	})
}

// 请求产品展示接口
function getProduct() {
    let curryFlavor = document.getElementById('curryFlavor');
    let faciaFlavor = document.getElementById('faciaFlavor');
    let fruitFlavor = document.getElementById('fruitFlavor');
    let hotFlavor = document.getElementById('hotFlavor');
    let noshFlavor = document.getElementById('noshFlavor');
    let southMilkFlavor = document.getElementById('southMilkFlavor');
    Ajax.get(apiUrl + '/api/product/getProduct', function (data) {
        let response = JSON.parse(data).data;
        curryFlavor.innerHTML = response.curryFlavor;
        faciaFlavor.innerHTML = response.faciaFlavor;
        fruitFlavor.innerHTML = response.fruitFlavor;
        hotFlavor.innerHTML = response.hotFlavor;
        noshFlavor.innerHTML = response.noshFlavor;
        southMilkFlavor.innerHTML = response.southMilkFlavor;
    });
}

// 渲染轮播图
function renderSwiper(responseText) {
    let swiper_wrapper = document.getElementsByClassName('swiper-wrapper')[0];
    let swiper_slide_list = responseText;
    let swiper_slide = '';
    swiper_slide_list.forEach(item => {
        swiper_slide += `<div class="swiper-slide"><img src="${apiUrl + item.value}" alt="颜小小"></div>`;
    });
    swiper_wrapper.innerHTML = swiper_slide;
    const mySwiper = new Swiper('.swiper-container', {
        autoplay: true,
        loop: true,
        // 如果需要分页器
        pagination: {
            el: '.swiper-pagination'
        }
    });
}

// 品牌故事
function renderBrandStoryDocument(responseText) {
    let brandStoryDocument = document.getElementById('brandStoryDocument');
    brandStoryDocument.innerHTML = responseText;
}
// 渲染导航栏
function renderNavigationBar(responseList) {
    let menuUl = document.getElementsByClassName('menu-list')[0];
    let page_item_title = document.getElementsByClassName('item-page-title');
    let titleIndex = 0;
    let menuHtml = `<li class="menu active">颜小小炸鸡</li>`;
    responseList.forEach((item, index) => {
        menuHtml += `<li class="menu">${item.value}</li>`;
        if(index !== 1) {
            page_item_title[titleIndex].innerText = item.value;
            titleIndex++;
        }
    });
    menuUl.innerHTML = menuHtml;
    menuClick();
}

// 获取每个主题页的offsetTop
function checkItemPageNodeInfo() {
    let item_page = document.getElementsByClassName('item-page');
    itemPageScrollTopArr = [];
    for (let i = 0; i < item_page.length; i++) {
        itemPageScrollTopArr.push(item_page[i].offsetTop);
    }
}
// 绑定导航栏点击事件
function menuClick() {
    let menu = document.getElementsByClassName('menu');
    for (let i = 0; i < menu.length; i++) {
        menu[i].index = i;
        addEvent(menu[i], 'click', function() {
            for (let j = 0; j < menu.length; j++) {
                if(this.index === menu[j].index) {
                    this.className = 'menu active';
                }else {
                    menu[j].className = 'menu';
                }
            }
            if(this.index === 0) return;
            window.scrollTo({
                top: itemPageScrollTopArr[this.index - 1],
                behavior: 'smooth'
            })
        })
    }
}

// 绑定返回顶部的点击事件
function backTopClick () {
    let backTopBtn = document.getElementById('backTop');
    addEvent(backTopBtn, 'click', function () {
        function smoothscroll () {
            let scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
            if (scrollTop > 0) {
                window.requestAnimationFrame(smoothscroll);
                window.scrollTo(0, scrollTop - scrollTop / 5);
            }
        }
        smoothscroll()
    });
}

// 返回顶部二维码鼠标移入事件
function backTopQRCode() {
    let QRcode = document.getElementsByClassName('QRcode')[0];
    let wxCode = document.getElementById('wxCode');
    addEvent(QRcode, 'mouseenter', function () {
        wxCode.style.cssText = 'display: block;';
    });
    addEvent(QRcode, 'mouseleave', function () {
        wxCode.style.cssText = 'display: none;';
    })
}

// 返回顶部控件的显示隐藏
function backToTop () {
    let backTopElm = document.getElementsByClassName('back-top')[0];
    let scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
    if (scrollTop >= clientHeight) {
        backTopElm.style.cssText = 'display: flex;';
    } else {
        backTopElm.style.cssText = 'display: none;';
    }
}

window.onload = function () {
    getResponse();
    getLeague();
    getOfficialInfo();
    getProduct();
    backTopClick();
    getClientHeight();
    backToTop();
    backTopQRCode();
};

window.onresize = function () {
    getClientHeight();
    checkItemPageNodeInfo();
};

window.onscroll = function () {
    backToTop();
};